package com.dhy.qigsaw.splash

import android.content.Context
import android.util.Log
import androidx.annotation.IdRes
import androidx.annotation.Keep
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.dhy.compatbundle.updateQigsawSplits
import com.dhy.qigsaw.splash.ApiUtil.AppConfig
import com.google.android.play.core.splitinstall.SplitInstallManager
import com.google.android.play.core.splitinstall.SplitInstallRequest
import okhttp3.ResponseBody
import org.json.JSONObject
import java.io.File

@Keep
abstract class ISplashFragment : Fragment() {
    abstract fun startSplash(activity: AppCompatActivity, dynamicFeatures: List<String>, @IdRes containerViewId: Int)
}

fun SplitInstallRequest.Builder.addModules(moduleNames: Collection<String>): SplitInstallRequest.Builder {
    moduleNames.forEach { addModule(it) }
    return this
}

fun SplitInstallManager.isAllInstalled(): Boolean {
    return installedModules == AppConfig.DYNAMIC_FEATURES.toSet()
}

fun String.splitInfoMd5(): String {
    // "http://www.qigsaw.com/acom.dhy.qigsaw2test-split-t0-v1.0-c1-330693fb43fa098b28728fdc45315a20.apk"
    return substring(lastIndexOf('-') + 1, lastIndexOf('.'))
}

/**
 * 插件是否兼容当前 BaseApp
 * */
fun File.isCompatSplitInfo(): Boolean {
    return try {
        val json = JSONObject(readText())
        val qigsawId = json.optString("qigsawId")
        qigsawId == AppConfig.QIGSAW_ID
    } catch (e: Exception) {
        e.printStackTrace()
        false
    }
}

fun Context.updateQigsawSplits(splitInfo: ResponseBody): Boolean {
    return splitInfo.use {
        if (it.contentLength() > 0) {
            val file = File.createTempFile("defaultQigsawSplitInfo", ".json")
            file.writeBytes(it.bytes())
            if (file.isCompatSplitInfo()) {
                updateQigsawSplits(file)
                true
            } else {
                Log.e(TAG, "incompat split info")
                file.delete()
                false
            }
        } else false
    }
}

internal const val TAG = "splash"